/**
 * Copyright (c) 2016-2019 优博信息科技 All rights reserved.
 *
 * https://www.jnyoubo.com
 *
 * 版权所有，侵权必究！
 */

package com.youbo.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.youbo.common.utils.*;
import com.youbo.common.validator.ValidatorUtils;
import com.youbo.config.UserConfig;
import com.youbo.entity.*;
import com.youbo.form.*;
import com.youbo.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * his 接口
 *
 * @author macy
 */
@RestController
@RequestMapping("/v1/api")
@Api(tags="健康济宁服务接口文档",position = 0)
public class ApiV1Controller {
    private Logger logger = LoggerFactory.getLogger(getClass());
    SimpleDateFormat df = new SimpleDateFormat(DateUtils.DATE_TIME_PATTERN);


    @Autowired
    private ApiV1Service apiV1Service;
    @Autowired
    private BrdaService brdaService;
    @Autowired
    private BrzhService brzhService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderMxService orderMxService;
    @Autowired
    private MzxxService mzxxService;
    @Autowired
    private SfmxService sfmxService;
    @Autowired
    private TbkkService tbkkService;
    @Autowired
    private BrryService brryService;

    @Autowired
    private Yj01Service yj01Service;
    @Autowired
    private Yj02Service yj02Service;
    @Autowired
    private Cf01Service cf01Service;
    @Autowired
    private Cf02Service cf02Service;

    @Autowired
    private GhmxService ghmxService;
    @Autowired
    private JhjlService jhjlService;
    @Autowired
    private XnysService xnysService;
    @Autowired
    private YyGhService yyGhService;
    @Autowired
    private UserConfig userConfig;




    @RequestMapping(value = "hospital",method = {RequestMethod.POST})
    @ApiOperation("机构信息上传接口 testOk")
    public R hospital(){
        String send=JsonTools.obj2String(userConfig.getHospitalClass());
        logger.debug(send);
        String json=HttpUtils.post(userConfig.getHospital(),send);
        return R.ok().putData(json);
    }


    @RequestMapping(value = "addAndUpdate",method = {RequestMethod.POST})
    @ApiOperation("科室医生增加、修改接口 testOk")
    public R addAndUpdate(){


        List<XnysEntity>  list=xnysService.list();
        if(null==list&&list.size()<=0){
            return R.ok(R.ERROR2,"查询成功,但没有信息");
        }

        List list1=new ArrayList();
        List list2=null;
        HashMap<String,Object> map=null;
        HashMap<String,Object> map2=null;
        for (XnysEntity xnys:list){
            map=new HashMap<>();
            map2=new HashMap<>();
            list2=new ArrayList();

            list1.add(map);
            list2.add(map2);

            map.put("typeCode","01");
            map.put("typeName","内科");
            map.put("deptCode",xnys.getKsid());
            map.put("deptName",xnys.getKsmc());
            map.put("hosCode",userConfig.getHospitalId());
            map.put("hosName",userConfig.getHospitalClass().getHosName());
            map.put("doctors",list2);

            map2.put("docCode",xnys.getYsid());
            map2.put("docName",xnys.getYsxm());
            map2.put("sex","9");
            map2.put("birthDate","19900101");
            map2.put("technicalTitle","5");


        }
        String send=JsonTools.obj2String(JsonTools.obj2String(list1));
        logger.info(send);
        String json=HttpUtils.post(userConfig.getAddAndUpdate(),send);
        return R.ok().putData(json);
    }

    @RequestMapping(value = "delete",method = {RequestMethod.POST})
    @ApiOperation("科室医生删除接口")
    public R delete(@RequestParam("docCode") String docCode){

        HashMap<String,String> hashMap=new HashMap<>();
        hashMap.put("hosCode",userConfig.getHospitalId());
        hashMap.put("deptCode","");
        hashMap.put("doctors","[{\"docCode\":\""+docCode+"\"}]");

        String json=HttpUtils.post(userConfig.getDelete(),JsonTools.obj2String(hashMap));
        return R.ok().putData(json);
    }


    /**
     * 每日凌晨4点执行上传医生排版信息
     */
    @Scheduled(cron = "0 0 4 * * ?")
    public void execute() {
        Date date=DateUtils.addDateDays(new Date(),7);
        insertSchedule(DateUtils.format(date,"yyyyMMdd"));
    }


    @RequestMapping(value = "insertSchedule",method = {RequestMethod.POST})
    @ApiOperation("医生排班信息上传接口(预约挂号)")
    public R insertSchedule(@RequestParam("date")  String date){


        if(StringUtils.isBlank(date)){
            return R.ok(R.ERROR3,"日期不能为空");
        }

        List<XnysEntity>  list=xnysService.list();
        if(null==list&&list.size()<=0){
            return R.ok(R.ERROR2,"查询成功,但没有信息");
        }


        Date dateTime=DateUtils.stringToDate(date,"yyyyMMdd");
        String sdate=DateUtils.format(dateTime)+" 00:00:00";
        String edate=DateUtils.format(dateTime)+" 23:59:59";
        String week=DateUtils.getWeekOfDateInt(new Date());


        List list1=new ArrayList();
        HashMap<String,Object> map1=null;
        HashMap<String,Object> map2=null;
        for (XnysEntity xnys:list){
            map1=new HashMap<>();
            map2=new HashMap<>();

            map1.put("hosCode",userConfig.getHospitalId());
            map1.put("hosName",userConfig.getHospitalClass().getHosName());
            map1.put("deptCode",xnys.getKsid());
            map1.put("deptName",xnys.getKsmc());
            map1.put("docCode",xnys.getYsid());
            map1.put("docName",xnys.getYsxm());
            map1.put("scheduleDate",date);
            map1.put("amPm","AM");
            map1.put("opType",xnys.getYsid().indexOf("ZJ")>=0?"1":"2");
            map1.put("scheduleType","2");
            map1.put("arAmt",new BigDecimal(xnys.getGhf()).add(new BigDecimal(xnys.getZlf())).setScale(2));
            map1.put("upLimit","999");
            map1.put("appNum","0");

            List<Doctor2> list2=apiV1Service.todayRegisterGetDoctors(xnys.getKsid(),week,sdate,edate,"1");//查询上午
            if(null!=list2&&list2.size()>0){
                list1.add(map1);
            }
            List<Doctor2> list3=apiV1Service.todayRegisterGetDoctors(xnys.getKsid(),week,sdate,edate,"2");//查询下午
            if(null!=list3&&list3.size()>0){
                map2.putAll(map1);
                map2.put("amPm","PM");
                list1.add(map2);
            }
        }

        String send=JSON.toJSONString(list1);
        logger.info(send);
        
        String json=HttpUtils.post(userConfig.getInsertSchedule(),send);
        return R.ok().putData(json);
    }


    @RequestMapping(value = "remainApp",method = {RequestMethod.POST})
    @ApiOperation("医生挂号余量接口 (预约挂号)")
    public R remainApp(@RequestBody Pform pform){

        if(null==pform){
            return R.ok(R.ERROR3,"缺少查询参数");
        }

        //String scheduleDate=pform.getString("scheduleDate");
        String amPm=pform.getString("amPm");
        HashMap<String,Object> map1=new HashMap<>();
        if(amPm.equals("AM")){
            map1.put("startTime","08:00");
            map1.put("endTime","12:00");
            map1.put("hisTimeId","1");
        }else{
            map1.put("startTime","14:00");
            map1.put("endTime","18:00");
            map1.put("hisTimeId","2");
        }

        map1.put("upLimit","999");
        map1.put("appNum","0");

        List<Map> list=new ArrayList<>();
        list.add(map1);

        return R.ok().putData(list);
    }


    @RequestMapping(value = "appointmentInfo",method = {RequestMethod.POST})
    @ApiOperation("预约挂号")
    public R appointmentInfo(@RequestBody YyGhEntity pform){

        if(null==pform){
            return R.ok(R.ERROR3,"缺少查询参数");
        }

        if(null==pform.getMedicalCard()){
            return R.ok(R.ERROR3,"缺少卡号");
        }
        if(null==pform.getRecordId()){
            return R.ok(R.ERROR3,"缺少挂号ID");
        }

        pform.setRefundNo(IDUtils.getUUID32());

        if(!yyGhService.saveOrUpdate(pform)) {
            return R.ok(R.ERROR3,"保存失败");
        }

        return R.ok().put("refundNo",pform.getRefundNo());
    }
    @RequestMapping(value = "querySurcharge",method = {RequestMethod.POST})
    @ApiOperation("querySurcharge")
    public R querySurcharge(){
        Map map=new HashMap();
        map.put("surcharge",0);
        return R.ok().putData(map);
    }

    @Transactional(rollbackFor={SQLException.class,Exception.class})
    @RequestMapping(value = "yyghRegister",method = {RequestMethod.POST})
    @ApiOperation("预约挂号支付")
    public R yyghRegister(@RequestBody Pform pform){

        if(null==pform){
            return R.ok(R.ERROR3,"缺少查询参数");
        }

        if(null==pform.getString("recordId")){
            return R.ok(R.ERROR3,"缺少挂号ID");
        }
        String recordId=pform.getString("recordId");
        String medicalCardNumber=pform.getString("medicalCardNumber");
        String idCard=pform.getString("idCard");
        String patientName=pform.getString("patientName");
        String deptCode=pform.getString("deptCode");
        String docCode=pform.getString("docCode");
        String arAmt=pform.getString("arAmt");
        String scheduleDate=pform.getString("scheduleDate");
        String payId=pform.getString("payId");
        String payState=pform.getString("payState");//支付状态，0未支付 1已支付 2支付失败 3支付成功，院内处理中 4院内理失败 5已退款
        String startTime=pform.getString("startTime");
        String amPm=pform.getString("amPm");
        String stateTime=pform.getString("stateTime");//支付时间，格式：yyyy-MM-dd HH:mm:ss
        String payType=pform.getString("payType");//支付方式.AliPay 支付宝，WeChatPay 微信，SelfBuiltPlatformPay自定义平台支付
        String surcharge=pform.getString("surcharge");
        String external=pform.getString("external");

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMdd HH:mm");

        HisUser hisUser=brdaService.queryHisUserByMedicalCardNumber(pform.getString("medicalCardNumber"));
        if(null==hisUser){
            hisUser=brdaService.queryHisUserByIdcard(pform.getString("idCard"));
            if(null==hisUser){
                return R.error(R.ERROR3,"根据电子卡号未查询到病人信息");
            }
        }

        OrderEntity order2=orderService.getOne(new QueryWrapper<OrderEntity>().eq("remarks",recordId).eq("type","预约挂号"));
        if(null!=order2){
            return R.error(R.ERROR2,"预约挂号已处理");
        }

        YyGhEntity yyGhEntity=yyGhService.getById(recordId);
        if(null!=yyGhEntity){
            yyGhEntity.setState(payState);
            yyGhEntity.setPayId(payId);
            yyGhService.updateById(yyGhEntity);
        }



        R res=R.ok(R.OK_SUCCESS,"成功");
        HashMap map=new HashMap<>();


        if(payState.equals("1")){//支付成功在挂号

            String sbxh=IDUtils.getPrimaryKey();

            //保存好挂号订单
            OrderEntity order=new OrderEntity();
            order.setType("预约挂号");
            order.setOutTradeNo(payId);
            order.setPayAmount(new BigDecimal(arAmt));
            order.setAmount(new BigDecimal(arAmt));
            try{
                order.setPayTime(df.parse(stateTime));
            }catch (Exception e){}

            order.setPayType(payType);
            order.setBalancePayment(new BigDecimal(0));
            order.setBrid(hisUser.getBrid());
            order.setCreateTime(new Date());
            order.setRemarks(recordId);
            order.setFphm(sbxh);
            orderService.save(order);

            BrzhEntity brzh=brzhService.getById(hisUser.getBrid());
            if(null!=brzh){
                brzh.setLjfy(brzh.getLjfy().add(order.getPayAmount()));
                brzhService.updateById(brzh);
            }

            GhmxEntity ghmx=new GhmxEntity();
            ghmx.setSbxh(sbxh);
            ghmx.setBrid(String.valueOf(hisUser.getBrid()));
            ghmx.setBrxz(hisUser.getBrxz());
            ghmx.setJzhm(IDUtils.getPrimaryKey());
            ghmx.setJzxh("0");
            try {
                Date ghsj=df2.parse(scheduleDate+" "+startTime);
                ghmx.setGhsj(ghsj);
            } catch (Exception eee) {
                ghmx.setGhsj(new Date());
            }

            XnysEntity xnys=xnysService.getOne(new QueryWrapper<XnysEntity>()
                    .eq("ysid",docCode)
            );

            if(null!=xnys){
                ghmx.setYsdm(xnys.getYsdm());
                ghmx.setGhlb((null!=xnys&&"专家号".equals(xnys.getGhlb())?"3":"1"));
                ghmx.setKsdm(xnys.getKsid2());
            }
            ghmx.setXjje(order.getPayAmount());
            ghmx.setGhcs("1");
            //ghmx.setYybz("9");//预约标志=9
            ghmx.setMzlb("9");
            ghmx.setCzgh("BSSA");

            ghmxService.save(ghmx);

            map.put("hisRegistrationId",ghmx.getSbxh());
            map.put("invoiceId",order.getOrderid());
            res.putData(map);
            return res;
        }

        return R.error(R.ERROR2,"非支付成功状态无需处理");
    }

    @RequestMapping(value = "yyghRefund",method = {RequestMethod.POST})
    @ApiOperation(value = "退款接口 （预约挂号）",notes="{\"businessNo\":\"123\"}")
    public R yyghRefund(@RequestBody Pform pform){

        if(null==pform){
            return R.error(R.ERROR3,"参数不能为空");
        }

        String businessNo=pform.getString("businessNo");
        if(null==businessNo){
            return R.error(R.ERROR3,"缺少商户订单号");
        }


        YyGhEntity yyGhEntity=yyGhService.getOne(new QueryWrapper<YyGhEntity>().eq("payId",businessNo));
        if(null==yyGhEntity){
            return R.error(R.ERROR3,"没有查询到订单");
        }

        if(yyGhEntity.getState().equals("5")){
            return R.error(R.ERROR3,"订单已退款");
        }else if(!yyGhEntity.getState().equals("1")){
            return R.error(R.ERROR3,"订单未支付");
        }

        OrderEntity order=orderService.getOne(new QueryWrapper<OrderEntity>().eq("remarks",yyGhEntity.getRecordId()).eq("type","预约挂号"));
        if(null==order){
            return R.error(R.ERROR3,"没有查询到订单");
        }

        Map<String,Object> map=new HashMap<>();
        map.put("businessNo",pform.getString("businessNo"));
        map.put("amount",order.getPayAmount());
        map.put("refundNo",yyGhEntity.getRefundNo());

        String json=HttpUtils.post(userConfig.getServiceIp()+"prefront/hospitalizationCosts/yyghRefund",JSON.toJSONString(map));
        if(null==json){
            return R.error(R.ERROR3,"退款失败");
        }
        try {
            HashMap res=JSON.parseObject(json,HashMap.class);
            if(!Boolean.valueOf(res.get("success").toString())){
                return R.error(R.ERROR3,"退款失败"+res.get("msg").toString());
            }

            yyGhEntity.setState("5");

        }catch (Exception e){
            return R.error(R.ERROR3,"退款失败"+e.getMessage());
        }

        return R.ok("退款成功");
    }


    @RequestMapping(value = "getStopDiagnosis",method = {RequestMethod.POST})
    @ApiOperation("停诊接口 （预约挂号）")
    public R getStopDiagnosis(){
        String json=HttpUtils.post(userConfig.getGetStopDiagnosis(),null);
        return R.ok().putData(json);
    }

    @RequestMapping(value = "getAppointResult",method = {RequestMethod.POST})
    @ApiOperation("就诊结果上传接口 （预约挂号）")
    public R getAppointResult(){
        String json=HttpUtils.post(userConfig.getGetAppointResult(),null);
        return R.ok().putData(json);
    }



    @RequestMapping(value = "getPatientInfo",method = {RequestMethod.POST})
    @ApiOperation("通过就诊卡号查询用户信息（调用公众号接口）")
    public Object getPatientInfo(@RequestParam String medicalCardNumber){
        String response=apiV1Service.getPatientInfo(medicalCardNumber);
        try {
            return JsonTools.string2Obj(response, HashMap.class);
        } catch (Exception e) {
            return R.error("错误:"+e.getMessage());
        }
    }






    /**
     * 办理电子健康卡 医院提供接口，根据公众号传来的办卡相关信息在院内建卡，建卡后用户持该卡的二维码可以在本院 就诊使用。 备注：新生儿办卡时，会输入母亲的身份证号和胎次，调用院内办卡接口时传入的身份证号参数是母 亲身份证+胎次，idcard 长度为 20 位，如：37010219860505123401
     *
     */


    /**
     * 办理电子健康卡 ok
     * @param createCardForm
     * @return
     */
    @RequestMapping(value = "createCard",method = {RequestMethod.POST})
    @ApiOperation("办理电子健康卡 testOk")
    public Object createCard(@RequestBody CreateCardForm createCardForm){


        //表单校验
        ValidatorUtils.validateEntity(createCardForm);

        //检查是否存在此用户
        if(null!=brdaService.queryMedicalCardNumber(createCardForm.getMedicalCardNumber())){
            return R.ok(R.ERROR9,"成功,已有此卡");
        }

        if(null!=createCardForm.getIdcard()&&!createCardForm.getIdcard().equals("")){
            //检查是否存在此用户
            BrdaEntity brdaEntity=brdaService.queryIdCardNo(createCardForm.getIdcard());
            if(null!=brdaEntity){
                brdaService.updateBrzhCardNumbrer(brdaEntity.getBrid(),createCardForm.getMedicalCardNumber());
                return R.ok(R.OK_SUCCESS,"成功,已有此身份用户已创建此卡,并绑定成功");
            }
        }

        if(!brdaService.saveBrdn(createCardForm)){
            return R.error(R.ERROR3,"创建失败");
        }


        return R.ok(R.OK_SUCCESS,"成功");
    }


    /**
     * 绑定实体就诊卡 为使用户可以使用已有实体就诊卡实现区域内无障碍就诊，公众号提供绑卡功能。 用户在公众号系统可以进行实体就诊卡的绑定。进行绑定时需要进行身份的验证。验证通过后，公众 号系统将根据实体卡生成电子健康卡，并主动将电子卡信息推送到院内。院内系统负责保证电子就诊 卡和实体卡的用户身份一致。
     *
     */



    /**
     * 根据就诊卡号查询用户信息  (查询院内)  ok
     * @param pform
     * @return
     */
    @RequestMapping(value = "queryPatientInfo",method = {RequestMethod.POST})
    @ApiOperation("根据就诊卡号查询用户信息 testOK")
    public Object queryPatientInfo(@RequestBody Pform pform){


        if(null==pform){
            return R.error(R.ERROR3,"参数不能为空");
        }

        if(null==pform.getString("medicalCardNumber")){
            return R.error(R.ERROR3,"电子卡号不能为空");
        }

        HisUser hisUser=brdaService.queryHisUserByKh(pform.getString("medicalCardNumber"));
        if(null==hisUser){
            hisUser=brdaService.queryHisUserByMedicalCardNumber(pform.getString("medicalCardNumber"));
            if(null==hisUser){
                return R.error(R.ERROR3,"未查询到信息");
            }
        }
        if(null!=hisUser){
            hisUser.setMedicalCardNumber(pform.getString("medicalCardNumber"));
            hisUser.setHospitalId(userConfig.getHospitalId());
        }
        return R.ok(R.OK_SUCCESS,"成功").putData(hisUser);
    }


    /**
     * 推送电子就诊卡信息  ok
     * @param bindCardForm
     * @return
     */
    @RequestMapping(value = "bindCard",method = {RequestMethod.POST})
    @ApiOperation("推送电子就诊卡信息 testOK")
    public Object bindCard(@RequestBody BindCardForm bindCardForm){


        //表单校验
        ValidatorUtils.validateEntity(bindCardForm);



        BrdaEntity brdaEntity=brdaService.queryMedicalCardNumber(bindCardForm.getNewMedicalCardNumber());
        if(null==brdaEntity){
            /**
             * 查询病人基本信息
             */
            String response=apiV1Service.getPatientInfo(bindCardForm.getNewMedicalCardNumber());
            R res=JsonTools.string2Obj(response,R.class);
            if(!res.getSuccess()){
                return R.ok(R.ERROR3,"无法同步用户信息,请检查getPatientInfo接口");
            }
            CreateCardForm createCardForm=JsonTools.string2Obj(JsonTools.obj2String(res.getData()),CreateCardForm.class);
            if(null!=createCardForm.getIdcard()&&!createCardForm.getIdcard().equals("")){
                //检查是否存在此用户
                brdaEntity=brdaService.queryIdCardNo(createCardForm.getIdcard());
                if(null!=brdaEntity){
                    brdaService.updateBrzhCardNumbrer(brdaEntity.getBrid(),createCardForm.getMedicalCardNumber());
                }else{
                    if(!brdaService.saveBrdn(createCardForm)){
                        return R.error(R.ERROR3,"创建失败");
                    }
                }
            }else{
                //创建新的 病人档案
                if(!brdaService.saveBrdn(createCardForm)){
                    return R.error(R.ERROR3,"创建失败");
                }
            }
        }

        Map data=new HashMap<>();
        data.put("createDate", DateUtils.format(new Date(),DateUtils.DATE_TIME_PATTERN));

        return R.ok(R.OK_SUCCESS,"成功").putData(data);
    }


    /**
     * 门诊缴费 用户在公众号系统中可以查询需要缴纳的费用并进行支付。支付成功后公众号系统调用院内接口 将支付结果推送到院内。院内系统必须准确的返回处理结果。如果未返回预期院内成功结果或院内系 统返回了处理失败，公众号系统将调用“退费查询接口”查询是否可以退费，如果返回可以退款将进 行退款。
     */


    /**
     * 待缴费信息查询接口
     * @param createCardForm
     * @return
     */
    @RequestMapping(value = "queryWaitPay",method = {RequestMethod.POST})
    @ApiOperation("待缴费信息查询接口 testOK")
    @Transactional(rollbackFor= SQLException.class)
    public Object queryWaitPay(@RequestBody CreateCardForm createCardForm){



        if(null==createCardForm){
            return R.error(R.ERROR3,"参数不能为空");
        }

        if(null==createCardForm.getMedicalCardNumber()){
            return R.error(R.ERROR3,"电子卡号不能为空");
        }

        HisUser hisUser=brdaService.queryHisUserByMedicalCardNumber(createCardForm.getMedicalCardNumber());
        if(null==hisUser){
            return R.error(R.ERROR3,"根据电子卡号未查询到病人信息");
        }

        String orderId=IDUtils.getUUId();

        //查询今天的
        String date=DateUtils.format(DateUtils.addDateDays(new Date(),0),DateUtils.DATE_PATTERN)+" 00:00:00";

        /**
         * 暂时不清除记录
         */
        //apiV1Service.clrOrderMx();

        /**
         * 导入待缴费 到 订单表
         */
        apiV1Service.importBrOrder(hisUser.getBrid(),Long.valueOf(orderId),date);


        List<Detail> listData=apiV1Service.queryOrderMxByBrid(hisUser.getBrid().toString(),orderId);
        if(null!=listData&&listData.size()<=0){
            return R.ok(R.ERROR2,"查询成功,但没有信息");
        }


        R res=R.ok(R.OK_SUCCESS,"成功");
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("amount",0);
        map.put("detail",listData);
        if(null!=listData){
            BigDecimal sum=new BigDecimal(0);
            for (Detail detail:listData){
                sum=sum.add(new BigDecimal(detail.getAmount()));
            }
            map.put("amount",sum.setScale(2, RoundingMode.HALF_UP).doubleValue());
        }

        res.putData(map);
        return res;
    }



    /**
     * 门诊支付成功通知  test ok
     * @param paymentForm
     * @return
     */
    @RequestMapping(value = "clinicPayment",method = {RequestMethod.POST})
    @ApiOperation("门诊支付成功通知 testOK")
    @Transactional(rollbackFor={SQLException.class,Exception.class})
    public Object clinicPayment(@RequestBody Payment paymentForm){

        if(null==paymentForm){
            return R.error(R.ERROR3,"参数不能为空");
        }

        if(null==paymentForm.getMedicalCardNumber()){
            return R.error(R.ERROR3,"电子卡号不能为空");
        }

        if(null==paymentForm.getDetailId()){
            return R.error(R.ERROR3,"待缴费明细中id不能为空");
        }

        HisUser hisUser=brdaService.queryHisUserByMedicalCardNumber(paymentForm.getMedicalCardNumber());
        if(null==hisUser){
            return R.error(R.ERROR3,"根据电子卡号未查询到病人信息");
        }


        R res=R.ok(R.OK_SUCCESS,"成功");
        Map<String,Object> map=new HashMap<String,Object>();


        OrderMxEntity orderMx=null;
        MzxxEntity mzxx=null;
        Yj01Entity yj01=null;
        Yj02Entity yj02=null;
        Cf01Entity cf01=null;
        Cf02Entity cf02=null;
        GhmxEntity ghmx=null;
        JhjlEntity jhjl=null;

        String mzxh=IDUtils.getPrimaryKey();
        String fphm=IDUtils.getPrimaryKey();



        OrderEntity isOrder=orderService.getOne(new QueryWrapper<OrderEntity>()
            .eq("outTradeNo",paymentForm.getOutTradeNo())
        );
        if(null!=isOrder){
            return R.error(R.ERROR3,"订单已处理");
        }

        OrderEntity order=new OrderEntity();
        order.setBrid(hisUser.getBrid());
        order.setType("门诊缴费");
        order.setFphm(fphm);
        order.setAmount(new BigDecimal(paymentForm.getAmount()));
        order.setPayAmount(new BigDecimal(paymentForm.getAmount()));
        order.setBalancePayment(new BigDecimal(paymentForm.getBalancePayment()));
        order.setPayType(paymentForm.getPayType());
        order.setPayTime(DateUtils.stringToDate(paymentForm.getPayTime(),DateUtils.DATE_TIME_PATTERN));
        order.setOutTradeNo(paymentForm.getOutTradeNo());

        if(!orderService.save(order)){
            return R.error(R.ERROR3,"订单信息无法保存");
        }


        for (int i=0;i<paymentForm.getDetailId().length;i++){
            String[] ids=paymentForm.getDetailId()[i].split("_");
            orderMx=orderMxService.getMxByWhere1(ids[0],ids[1]);

            if(null==orderMx){
                logger.error("订单明细未查询到数据:"+paymentForm.getDetailId()[i]);
                continue;
            }
            orderMx.setOrderid(order.getOrderid()+"");
            orderMxService.updateById(orderMx);


            if("YJ".equals(orderMx.getType())){
                yj01=yj01Service.getById(orderMx.getXh());
                if(null!=yj01){
                    yj01.setFphm(fphm);
                    yj01.setMzxh(mzxh);
                    //yj01.setCfbz("1");
                    //yj01.setZfpb("1");
                    yj01Service.updateById(yj01);
                }
                yj02=yj02Service.getById(orderMx.getId());
                if(null!=yj02){
                    yj02.setZfbl("1");
                    yj02Service.updateById(yj02);
                }
            }else if("CF".equals(orderMx.getType())){
                cf01=cf01Service.getById(orderMx.getXh());
                if(null!=cf01){
                    cf01.setFphm(fphm);
                    cf01.setMzxh(mzxh);
                    //cf01.setCfbz("1");
                    //cf01.setZfpb("1");
                    cf01.setFyck("0");
                    cf01Service.updateById(cf01);
                }
                cf02=cf02Service.getById(orderMx.getId());
                if(null!=cf02){
                    cf02.setZfbl("1");
                    cf02Service.updateById(cf02);
                }
            }

        }

        //修改累计消费
        BrzhEntity brzh=brzhService.getById(hisUser.getBrid());
        if(null!=brzh){
            if(null==brzh.getLjfy()){
                brzh.setLjfy(new BigDecimal(0));
            }
            brzh.setLjfy(brzh.getLjfy().add(order.getPayAmount()));
            brzhService.updateById(brzh);
        }

        //判断是否生成 检验记录
        List<OrderMxEntity> jycontList=orderMxService.list(new QueryWrapper<OrderMxEntity>()
                .eq("orderid",order.getOrderid().toString())
                .eq("type","YJ")
                .eq("sfxm","9")
        );

        if(null!=jycontList&&jycontList.size()>0){
            OrderMxEntity jycont=jycontList.get(0);
            jhjl=new JhjlEntity();
            jhjl.setDlid("3");
            HashMap pdhmMap=jhjlService.queryPdhm();
            if(null!=pdhmMap){
                jhjl.setPdhm(pdhmMap.get("pdhm").toString());
                jhjl.setPdxshm(pdhmMap.get("pdxshm").toString());
            }

            jhjl.setDlmc("检验");
            jhjl.setBrly("门诊");
            jhjl.setBrid(hisUser.getBrid());
            jhjl.setBrxm(hisUser.getName());
            if(null!=brzh){
                jhjl.setBrkh(brzh.getBrkh());
            }
            jhjl.setJhzt("1");
            jhjl.setYsdm("检验");
            jhjl.setSbxh("3");
            jhjl.setKsdm(jycont.getKsdm());
            jhjl.setKsmc("检验");
            jhjl.setDllx("检验");
            jhjl.setSj(new Date());
            jhjl.setJhnr("");
            //jhjlService.save(jhjl);
            jhjlService.insertJhjl(jhjl);
        }

        //生成门诊信息  和 汇总信息 并且回填发票号码
        mzxx=new MzxxEntity();
        mzxx.setBrid(String.valueOf(order.getBrid()));
        mzxx.setBrxm(hisUser.getName());
        mzxx.setBrxb(hisUser.getGender());
        mzxx.setBrxz(hisUser.getBrxz());

        mzxx.setMzxh(mzxh);  // 取门诊序号
        mzxx.setFphm(fphm);  // 取发票号码
        //mzxx.setSjfp(fphm);  // 取发票号码
        mzxx.setSfrq(order.getCreateTime());
        mzxx.setBrxz("9");//9=自费  10=职工医保  11=新农合  等等
        mzxx.setXjje(order.getAmount());//余额金额
        mzxx.setZfje(order.getAmount());
        mzxx.setMzlb("9");// 门诊类别
        mzxx.setCzgh("BSSA");//操作工号
        mzxx.setSffs(paymentForm.getPayType().equals("WeChatPay")?"5":"6");// 5=微信 6=支付宝

        ghmx=ghmxService.queryGhmxByBridTop1(String.valueOf(hisUser.getBrid()));
        if(null!=ghmx){
            mzxx.setGhgl(String.valueOf(ghmx.getSbxh()));
        }
        /**
         * 保存门诊信息 并导入 汇总项目 明细
         */
        mzxxService.save(mzxx);
        sfmxService.importBrSfmx(String.valueOf(order.getOrderid()),mzxh,fphm);


        if(null!=order){
            map.put("amount",order.getAmount());
        }
        if(null!=order){
            map.put("outPrepayId",order.getOrderid());
        }
        res.putData(map);
        return res;
    }







    /**
     *     当日挂号
     *
     *     实现患者在公众号里面直接挂号，公众号系统需要从院内 his 获取当天值班的号源，
     *     his 提供挂号接口，公众号系统将患者挂号相关信息--患者信息、医生科室信息、缴费
     *     信息传入 his 进行挂号，his 挂号返回 his 挂号是否成功信息给公众号系统。
     */

    /**
     * 查询当天可预约科室 test ok
     * @param pform  万能参数对象
     * @return
     */
    @RequestMapping(value = "todayRegisterGetDepts",method = {RequestMethod.POST})
    @ApiOperation("查询当天可预约科室 testOk")
    public Object todayRegisterGetDepts(@RequestBody Pform pform){


        if(null==pform){
            return R.error(R.ERROR3,"参数不能为空");
        }



        List<Dept2> list=apiV1Service.todayRegisterGetDepts();
        if(null!=list&&list.size()<=0){
            return R.ok(R.ERROR2,"查询成功,但没有信息");
        }

        Date date1= DateUtils.stringToDate(DateUtils.format(new Date())+" 08:00:00","yyyy-MM-dd HH:mm:ss");
        Date date2=DateUtils.stringToDate(DateUtils.format(new Date())+" 18:00:00","yyyy-MM-dd HH:mm:ss");
        Date date=new Date();


        String sdate=DateUtils.format(new Date())+" 00:00:00";
        String edate=DateUtils.format(new Date())+" 23:59:59";

        String week=DateUtils.getWeekOfDateInt(new Date());
        String pm=DateUtils.getPm();

        List<Dept2> listres=new ArrayList<>();
        for(Dept2 dept:list){

            if(date.after(date1)&&date.before(date2)){
                //"特出部门可以预约  其他不在服务时间范围都不能预约"
            }else{
//                if(!dept.getDeptTypeId().equals("2")&&!dept.getDeptTypeId().equals("16")){
//                    continue;
//                }
                //continue;
            }

            List<Doctor2> list2=apiV1Service.todayRegisterGetDoctors(dept.getDeptTypeId(),week,sdate,edate,pm);
            if(null!=list2&&list2.size()>0){
                listres.add(dept);
            }

            logger.info("查询一次:"+dept.getDeptTypeId()+" "+dept.getDeptTypeName()+" list:"+list2.size());

        }

        R res=R.ok(R.OK_SUCCESS,"成功").putData(listres);
        return res;
    }


    /**
     * 查询科室可预约医生 test ok
     * @param pform  万能参数对象
     * @return
     */
    @RequestMapping(value = "todayRegisterGetDoctors",method = {RequestMethod.POST})
    @ApiOperation("查询科室可预约医生 testOk")
    public Object todayRegisterGetDoctors(@RequestBody Pform pform){


        if(null==pform){
            return R.error(R.ERROR3,"参数不能为空");
        }
        String departmentId=pform.getString("departmentId");
        String sdate=DateUtils.format(new Date())+" 00:00:00";
        String edate=DateUtils.format(new Date())+" 23:59:59";
        String week=DateUtils.getWeekOfDateInt(new Date());
        String pm=DateUtils.getPm();

        List<Doctor2> list=apiV1Service.todayRegisterGetDoctors(departmentId,week,sdate,edate,pm);
        if(null!=list&&list.size()<=0){
            return R.ok(R.ERROR2,"查询成功,但没有信息");
        }
        R res=R.ok(R.OK_SUCCESS,"成功").putData(list);
        return res;
    }



    /**
     * 查询医生当天可预约号源  test ok
     * @param pform  万能参数对象
     * @return
     */
    @RequestMapping(value = "todayRegisterGetRemain",method = {RequestMethod.POST})
    @ApiOperation("查询医生当天可预约号源 testOk")
    public Object todayRegisterGetRemain(@RequestBody Pform pform){

        if(null==pform){
            return R.error(R.ERROR3,"参数不能为空");
        }
        pform.getString("departmentId");//科室编码
        pform.getString("hospitalId");
        pform.getString("doctorId");//医生编码
        pform.getString("regClassId");//挂号类型编码


        List<Map<String,Object>> data=new ArrayList<>();

        Map<String,Object> map=new HashMap<>();
        map.put("startTime","06:00");
        map.put("endTime","12:00");
        map.put("appNum","9999");//号源余量
        map.put("sequence","1");
        map.put("amPm","a");//上下午标志",a 上午/ p 下午/n 晚上
        map.put("timeCode","1");
        data.add(map);

        map=new HashMap<>();
        map.put("startTime","12:01");
        map.put("endTime","23:59");
        map.put("appNum","9999");//号源余量
        map.put("sequence","2");
        map.put("amPm","p");//上下午标志",a 上午/ p 下午/n 晚上
        map.put("timeCode","2");
        data.add(map);


        R res=R.ok(R.OK_SUCCESS,"成功").putData(data);
        return res;
    }


    /**
     * 当天患者挂号次数   test
     * @param pform  万能参数对象
     * @return
     */
    @RequestMapping(value = "todayRegisterCounts",method = {RequestMethod.POST})
    @ApiOperation("当天患者挂号次数 testOk")
    public Object todayRegisterCounts(@RequestBody Pform pform){


        if(null==pform){
            return R.error(R.ERROR3,"参数不能为空");
        }
        pform.getString("medicalCardNumber");
        pform.getString("idCard");

        HisUser hisUser=brdaService.queryHisUserByMedicalCardNumber(pform.getString("medicalCardNumber"));
        if(null==hisUser){
            hisUser=brdaService.queryHisUserByIdcard(pform.getString("idCard"));
            if(null==hisUser){
                return R.error(R.ERROR3,"根据电子卡号未查询到病人信息");
            }
        }

        List<GhmxEntity> list=ghmxService.list(new QueryWrapper<GhmxEntity>()
            .eq("brid",hisUser.getBrid())
            .ge("GHSJ",DateUtils.format(new Date())+" 00:00:00")
        );

        R res=R.ok(R.OK_SUCCESS,"成功");

        if(null!=list){
            res.putData(list.size());
        }else{
            res.putData(0);
        }
        return res;
    }

    /**
     * 挂号接口
     * @param pform  万能参数对象
     * @return
     */
    @RequestMapping(value = "todayRegisterToRegister",method = {RequestMethod.POST})
    @ApiOperation("挂号接口 testOk")
    @Transactional(rollbackFor={SQLException.class,Exception.class})
    public Object todayRegisterToRegister(@RequestBody Pform pform){


        if(null==pform){
            return R.error(R.ERROR3,"参数不能为空");
        }
        if(null==pform.getString("medicalCardNumber")){
            return R.error(R.ERROR3,"未查询到病人信息");
        }
        if(null==pform.getString("payState")){
            return R.error(R.ERROR3,"支付状态不能为空");
        }
        if(!"1".equals(pform.getString("payState"))){
            return R.error(R.ERROR3,"未交费无需处理");
        }

        HisUser hisUser=brdaService.queryHisUserByMedicalCardNumber(pform.getString("medicalCardNumber"));
        if(null==hisUser){
            hisUser=brdaService.queryHisUserByIdcard(pform.getString("idCard"));
            if(null==hisUser){
                return R.error(R.ERROR3,"根据电子卡号未查询到病人信息");
            }
        }

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        pform.getString("hospitalId");
//        pform.getString("patientName");
//        pform.getString("registrationDate");
//        pform.getString("regClassId");
//        pform.getString("regClassName");
//        pform.getString("registerTime");
//        pform.getString("scheduleType");
//        pform.getString("sequence");
//        pform.getString("timeCode");
//        pform.getString("amPm");

        String sbxh=IDUtils.getPrimaryKey();
        String payId=pform.getString("payId");

        List<OrderEntity> orderEntityLIst=orderService.list(new LambdaUpdateWrapper<OrderEntity>()
                .eq(OrderEntity::getOutTradeNo,payId)
        );
        if(null!=orderEntityLIst&&orderEntityLIst.size()>0){
            logger.error("支付重复通知 payId="+payId);

            R res=R.ok(R.OK_SUCCESS,"成功");
            HashMap map=new HashMap<>();
            map.put("hisRegistrationId",orderEntityLIst.get(0).getFphm());
            map.put("invoiceId",orderEntityLIst.get(0).getOrderid());
            res.putData(map);
            return res;
        }


        //保存好挂号订单
        OrderEntity order=new OrderEntity();
        order.setType("当日挂号");
        order.setOutTradeNo(payId);
        order.setPayAmount(new BigDecimal(pform.getString("registrationFee")));
        order.setAmount(new BigDecimal(pform.getString("registrationFee")));
        order.setPayTime(new Date());
        order.setPayType(pform.getString("payType"));
        order.setBalancePayment(new BigDecimal(0));
        order.setBrid(hisUser.getBrid());
        order.setCreateTime(new Date());
        order.setRemarks(pform.getString("todayRegisterId"));
        order.setFphm(sbxh);
        orderService.save(order);


        BrzhEntity brzh=brzhService.getById(hisUser.getBrid());
        if(null!=brzh){
            brzh.setLjfy(brzh.getLjfy().add(order.getPayAmount()));
            brzhService.updateById(brzh);
        }


        GhmxEntity ghmx=new GhmxEntity();
        ghmx.setSbxh(sbxh);
        ghmx.setBrid(String.valueOf(hisUser.getBrid()));
        ghmx.setBrxz(hisUser.getBrxz());
        ghmx.setJzhm(IDUtils.getPrimaryKey());
        ghmx.setJzxh("0");
        try {
            ghmx.setGhsj(df.parse(pform.getString("registrationDate")+DateUtils.format(new Date(),"HH:mm:ss")));
        } catch (ParseException e) {
            ghmx.setGhsj(new Date());
        }

        if(null!=pform.getString("doctorId")&&pform.getString("doctorId").indexOf("XN")==-1){
            ghmx.setYsdm(pform.getString("doctorId"));
        }

        XnysEntity xnys=xnysService.getOne(new QueryWrapper<XnysEntity>()
            .eq("ksid",pform.getString("departmentId"))
        );
        if(null!=xnys){
            ghmx.setGhlb((null!=xnys&&"专家号".equals(xnys.getGhlb())?"3":"1"));
            ghmx.setKsdm(xnys.getKsid2());
        }
        ghmx.setXjje(order.getPayAmount());
        ghmx.setGhcs("1");
        //ghmx.setYybz("9");//预约标志=9
        ghmx.setMzlb("9");
        ghmx.setCzgh("BSSA");

        ghmxService.save(ghmx);


        R res=R.ok(R.OK_SUCCESS,"成功");
        HashMap map=new HashMap<>();
        map.put("hisRegistrationId",ghmx.getSbxh());
        map.put("invoiceId",order.getOrderid());
        res.putData(map);
        return res;
    }




    /**
     * 查询科室挂号限制接口
     * @param pform  万能参数对象
     * @return
     */
    @RequestMapping(value = "todayRegisterGetDeptLimit",method = {RequestMethod.POST})
    @ApiOperation("查询科室挂号限制接口 testOk")
    public Object todayRegisterGetDeptLimit(@RequestBody Pform pform){
        if(null==pform){
            return R.error(R.ERROR3,"参数不能为空");
        }
        R res=R.ok(R.OK_SUCCESS,"成功");
        return res;
    }


    /**
     * 查询当前患者挂号此科室有无优惠信息，返回优惠后实际应该收取的费用
     * @param pform  万能参数对象
     * @return
     */
    @RequestMapping(value = "todayRegisterGetDiscount",method = {RequestMethod.POST})
    @ApiOperation("查询患者优惠信息接口 testOk")
    public Object todayRegisterGetDiscount(@RequestBody Pform pform){

        if(null==pform){
            return R.error(R.ERROR3,"参数不能为空");
        }
//        pform.getString("medicalCardNumber");//
//        pform.getString("departmentId");//科室编码
//        pform.getString("doctorId");//医生编码
//        pform.getString("opTyp");//门诊类型，1:专家门诊；2:普通门诊；3:特需门诊

        HisUser hisUser=brdaService.queryHisUserByMedicalCardNumber(pform.getString("medicalCardNumber"));
        if(null==hisUser){
            return R.error(R.ERROR3,"根据电子卡号未查询到病人信息");
        }

        R res=R.ok(R.OK_SUCCESS,"成功").putData(10);// 返回实际  挂号费用

        String departmentId=pform.getString("departmentId");
        String week=DateUtils.getWeekOfDateInt(new Date());
        String pm=DateUtils.getPm();

        HashMap<String,Object> map=apiV1Service.queryGhf(departmentId,week,pm);
        if(null==map){
            return R.error(R.ERROR3,"未查询到挂号费用");
        }
        if(null==map.get("ghf")||null==map.get("zlf")){
            return R.error(R.ERROR3,"未查询到挂号费用");
        }

        if(apiV1Service.queryGhFp(hisUser.getIdcard())>0){
            return res.putData(0); //扶贫全免费
        }
        if(apiV1Service.queryGhYz()==1){
            return res.putData(0); //义诊全免费
        }
        Double ghf=Double.valueOf(map.get("ghf").toString());
        Double zlf=Double.valueOf(map.get("zlf").toString());

//        if(apiV1Service.queryGhCsz()==1){
//            ghf=new Double(0);
//        }

        if(null!=hisUser.getIdcard()&&hisUser.getIdcard().length()>=18){
            if(IDUtils.getAge(hisUser.getIdcard())>=60){
                ghf=new Double(0);
            }
        }
        return res.putData((ghf+zlf));
    }






















    /***********************************   住院  ******************************************************/


    /**
     * 查询用户的住院信息
     * @param pform  万能参数对象
     * @return
     */
    @RequestMapping(value = "queryInpatientInfo",method = {RequestMethod.POST})
    @ApiOperation("查询用户的住院信息 testOk")
    public Object queryInpatientInfo(@RequestBody Pform pform){

        if(null==pform){
            return R.error(R.ERROR3,"参数不能为空");
        }

        if(null==pform.getString("medicalCardNumber")){
            return R.error(R.ERROR3,"电子卡号不能为空");
        }

        HisUser hisUser=brdaService.queryHisUserByMedicalCardNumber(pform.getString("medicalCardNumber"));
        if(null==hisUser){
            return R.error(R.ERROR3,"根据电子卡号未查询到病人信息");
        }

        BrryEntity brry=null;
        if(null!=pform.getString("admissionNumber")){
            brry=brryService.queryByZyhm(pform.getString("admissionNumber"));
        }
        if(null==brry){
            brry=brryService.queryBySfzh(hisUser.getIdcard());
        }
        if(null==brry){
            return R.error(R.ERROR2,"没有住院信息");
        }

        HashMap map=brryService.queryInpatientInfo(brry.getZyhm());
        if(null==map){
            return R.ok(R.ERROR2,"查询成功,但没有信息");
        }

        map.put("hospitalId",userConfig.getHospitalId());
        map.put("medicalCardNumber",hisUser.getMedicalCardNumber());

        R res=R.ok(R.OK_SUCCESS,"成功");
        res.putData(map);
        return res;
    }




    /**
     * 向院内写入住院押金缴纳信息
     * @param pform  万能参数对象
     * @return
     */
    @RequestMapping(value = "paymentOfDeposit",method = {RequestMethod.POST})
    @ApiOperation("向院内写入住院押金缴纳信息 testOK")
    public Object paymentOfDeposit(@RequestBody Pform pform) throws Exception {

        if(null==pform){
            return R.error(R.ERROR3,"参数不能为空");
        }
        if(null==pform.getString("medicalCardNumber")){
            return R.error(R.ERROR3,"电子卡号不能为空");
        }

        HisUser hisUser=brdaService.queryHisUserByMedicalCardNumber(pform.getString("medicalCardNumber"));
        if(null==hisUser){
            return R.error(R.ERROR3,"根据电子卡号未查询到病人信息");
        }

        BrryEntity brry=brryService.getOne(new QueryWrapper<BrryEntity>()
                .eq("SFZH",hisUser.getIdcard())
                .lt("cypb",8)
        );

        if(null==brry&&null!=pform.getString("admissionNumber")){
            brry=brryService.getOne(new QueryWrapper<BrryEntity>()
                    .eq("ZYHM",pform.getString("admissionNumber"))
                    .lt("cypb",8)
            );
        }
        if(null==brry){
            return R.error(R.ERROR2,"没有住院信息");
        }

        String jkxh=IDUtils.getPrimaryKey();

        //保存住院押金
        OrderEntity order=new OrderEntity();
        order.setType("住院押金");
        order.setOutTradeNo(pform.getString("outTradeNo"));
        order.setPayAmount(new BigDecimal(pform.getString("amount")));
        order.setAmount(new BigDecimal(pform.getString("amount")));
        order.setPayTime(df.parse(pform.getString("payTime")));
        order.setPayType(pform.getString("payType"));
        order.setBalancePayment(new BigDecimal(0));
        order.setBrid(hisUser.getBrid());
        order.setCreateTime(new Date());
        order.setRemarks(brry.getZyh());
        order.setFphm(jkxh);
        orderService.save(order);




        //Brry 想brry 信息里面 增加余额
        TbkkEntity tbkk=new TbkkEntity();
        tbkk.setJkje(pform.getString("amount"));
        tbkk.setJkxh(jkxh);
        tbkk.setZyh(brry.getZyh());
        tbkk.setJkrq(order.getPayTime());
        tbkk.setJkfs("7");// 默认现金
        tbkk.setSjhm(IDUtils.getPrimaryKey8());//实际号码
        tbkk.setZfpb("0");
        tbkk.setZcpb("0");
        tbkk.setCzgh("BSSA");


        if(!tbkkService.save(tbkk)){
            return R.error(R.ERROR3,"保存流水失败");
        }

        HashMap ma=brryService.queryInpatientInfo(brry.getZyhm());


        R res=R.ok(R.OK_SUCCESS,"成功");
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("outPrepayId",tbkk.getJkxh());
        if(null!=ma){
            map.put("amount",ma.get("prepayLeft"));
        }
        res.putData(map);
        return res;
    }

    /**
     *获取住院押金欠费用户信息
     * @return
     */
    @RequestMapping(value = "hospitalizationDepositIsLowerThan",method = {RequestMethod.POST})
    @ApiOperation("获取住院押金欠费用户信息  testOk")
    public Object hospitalizationDepositIsLowerThan(){

        R res=R.ok(R.OK_SUCCESS,"成功");
        List<HashMap> list=brryService.hospitalizationDepositIsLowerThan();
        if(null!=list){
            for (HashMap map:list){
                map.put("hospitalId",userConfig.getHospitalId());
            }
        }
        if(null!=list&&list.size()<=0){
            return R.ok(R.ERROR2,"查询成功,但没有信息");
        }

        res.putData(list);
        return res;
    }


    /**
     *查询所有住院状态的电子健康卡用户信息
     * @return
     */
    @RequestMapping(value = "inpatientList",method = {RequestMethod.POST})
    @ApiOperation("查询所有住院状态的电子健康卡用户信息 testOk ")
    public Object inpatientList(){

        R res=R.ok(R.OK_SUCCESS,"成功");
        List<HashMap> list=brryService.inpatientList();
        if(null!=list){
            for (HashMap map:list){
                map.put("hospitalId",userConfig.getHospitalId());
            }
        }
        if(null!=list&&list.size()<=0){
            return R.ok(R.ERROR2,"查询成功,但没有信息");
        }

        res.putData(list);
        return res;
    }


    /**
     *查询一日住院费用明细
     * @param pform  万能参数对象
     * @return
     */
    @RequestMapping(value = "dailycost",method = {RequestMethod.POST})
    @ApiOperation("查询一日住院费用明细 testOk ")
    public Object dailycost(@RequestBody Pform pform){

        if(null==pform){
            return R.error(R.ERROR3,"参数不能为空");
        }
        if(null==pform.getString("date")){
            return R.error(R.ERROR3,"查询日期不能为空");
        }
        if(null==pform.getString("medicalCardNumber")){
            return R.error(R.ERROR3,"电子卡号不能为空");
        }

        BrryEntity brry=null;
        HisUser hisUser=brdaService.queryHisUserByIdcard(pform.getString("idCard"));
        if(null==hisUser&&null!=pform.getString("medicalCardNumber")){
            hisUser=brdaService.queryHisUserByMedicalCardNumber(pform.getString("medicalCardNumber"));
        }
        if(null==hisUser&&null!=pform.getString("admissionNumber")){
            brry=brryService.queryByZyhm(pform.getString("admissionNumber"));
        }

        if(null==hisUser&&brry==null){
            return R.error(R.ERROR3,"根据身份证号未查询到病人信息");
        }
        if(null==brry){
            brry=brryService.queryBySfzh(hisUser.getIdcard());
        }
        if(null==brry){
            return R.error(R.ERROR3,"未查询到住院信息");
        }
        String sdate=pform.getString("date")+" 00:00:00";
        String edate=pform.getString("date")+" 23:59:59";

        HashMap map=brryService.queryByBr(brry.getZyh());
        if(null==map){
            return R.error(R.ERROR2,"未查询到住院信息");
        }

        List<HashMap> list=brryService.queryFyDetails(brry.getZyh(),sdate,edate);
        if(null!=list){
            double sum=0;
            for (HashMap m:list){
                sum=sum+Double.valueOf(m.get("amount").toString());
            }
            map.put("total",sum);
            map.put("details",list);
        }else{
            map.put("details",new ArrayList<>());
        }

        R res=R.ok(R.OK_SUCCESS,"成功");
        res.putData(map);
        return res;
    }




    /****************************   对账  ***********************************************/


    /**
     *时间段交易汇总查询接口
     * @param pform  万能参数对象
     * @return
     */
    @RequestMapping(value = "summary",method = {RequestMethod.POST})
    @ApiOperation("时间段交易汇总查询接口 testOk ")
    public Object summary(@RequestBody Pform pform){

        if(null==pform){
            return R.error(R.ERROR3,"参数不能为空");
        }

        if(null==pform.get("startTime")){
            return R.error(R.ERROR3,"开始时间不能为空");
        }
        if(null==pform.get("endTime")){
            return R.error(R.ERROR3,"结束时间不能为空");
        }

        HashMap<String,Object> map=apiV1Service.summary(pform.getString("startTime"),pform.getString("endTime"));

        if(null==map){
            return R.ok(R.ERROR2,"查询成功,但没有信息");
        }

        R res=R.ok(R.OK_SUCCESS,"成功");
        res.putData(map);
        return res;
    }


    /**
     * 时间段内交易按天汇总
     * @param pform  万能参数对象
     * @return
     */
    @RequestMapping(value = "dailySummary",method = {RequestMethod.POST})
    @ApiOperation("时间段内交易按天汇总 testOk ")
    public Object dailySummary(@RequestBody Pform pform){

        if(null==pform){
            return R.error(R.ERROR3,"参数不能为空");
        }

        if(null==pform.get("startTime")){
            return R.error(R.ERROR3,"开始时间不能为空");
        }
        if(null==pform.get("endTime")){
            return R.error(R.ERROR3,"结束时间不能为空");
        }

        List<HashMap<String,Object>> list=apiV1Service.dailySummary(pform.getString("startTime"),pform.getString("endTime"));
        if(null!=list&&list.size()<=0){
            return R.ok(R.ERROR2,"查询成功,但没有信息");
        }


        R res=R.ok(R.OK_SUCCESS,"成功");
        res.putData(list);
        return res;
    }


    /**
     * 指定时间段内交易记录查询接口
     * @param pform  万能参数对象
     * @return
     */
    @RequestMapping(value = "detail",method = {RequestMethod.POST})
    @ApiOperation("指定时间段内交易记录查询接口 testOk ")
    public Object detail(@RequestBody Pform pform){

        if(null==pform){
            return R.error(R.ERROR3,"参数不能为空");
        }

        if(null==pform.get("startTime")){
            return R.error(R.ERROR3,"开始时间不能为空");
        }
        if(null==pform.get("endTime")){
            return R.error(R.ERROR3,"结束时间不能为空");
        }
        List<HashMap<String,Object>> list=apiV1Service.detail(pform.getString("startTime"),pform.getString("endTime"));
        if(null!=list&&list.size()<=0){
            return R.ok(R.ERROR2,"查询成功,但没有信息");
        }
        R res=R.ok(R.OK_SUCCESS,"成功");
        res.putData(list);
        return res;
    }



    /**
     * 根据订单号查询订单
     * @param pform  万能参数对象
     * @return
     */
    @RequestMapping(value = "reconciliation",method = {RequestMethod.POST})
    @ApiOperation("根据订单号查询订单 testOk ")
    public Object reconciliation(@RequestBody Pform pform){

        if(null==pform){
            return R.error(R.ERROR3,"参数不能为空");
        }
        if(null==pform.getString("tradeNo")){
            return R.error(R.ERROR3,"订单号不能为空");
        }

        HashMap<String,Object> map=apiV1Service.reconciliation(pform.getString("tradeNo"));

        if(null==map){
            return R.ok(R.ERROR2,"查询成功,但没有信息");
        }

        R res=R.ok(R.OK_SUCCESS,"成功");
        res.putData(map);
        return res;
    }


    /**
     * 根据订单号和退款单号查询退款记录
     * @param pform  万能参数对象
     * @return
     */
    @RequestMapping(value = "queryByOutTradeNoAndRefundNo",method = {RequestMethod.POST})
    @ApiOperation("根据订单号和退款单号查询退款记录  （暂不支持）")
    public Object queryByOutTradeNoAndRefundNo(@RequestBody(required = false) Pform pform){
        return R.error(R.ERROR3,"暂不支持");
    }



    /****************************   费用查询  ***********************************************/





    /**
     *  查询指定患者指定时间范围内的门诊费用
     * @param pform  万能参数对象
     * @return
     */
    @RequestMapping(value = "queryOutpatientCostDetail",method = {RequestMethod.POST})
    @ApiOperation("查询指定患者指定时间范围内的门诊费用 testOk ")
    public Object queryOutpatientCostDetail(@RequestBody Pform pform){

        if(null==pform){
            return R.error(R.ERROR3,"参数不能为空");
        }
        if(null==pform.getString("medicalCardNumber")&&null==pform.getString("idCard")){
            return R.error(R.ERROR3,"电子卡号不能为空");
        }
        if(null==pform.getString("startTime")){
            return R.error(R.ERROR3,"查询日期不能为空");
        }
        if(null==pform.getString("endTime")){
            return R.error(R.ERROR3,"查询日期不能为空");
        }

        HisUser  hisUser=brdaService.queryHisUserByMedicalCardNumber(pform.getString("medicalCardNumber"));
        if(null==hisUser&&null!=pform.getString("idCard")){
            hisUser=brdaService.queryHisUserByIdcard(pform.getString("idCard"));
        }
        if(null==hisUser){
            return R.error(R.ERROR3,"未查询到病人信息");
        }


        List<HashMap> list=orderService.queryOutpatientCost(String.valueOf(hisUser.getBrid()),pform.getString("startTime"),pform.getString("endTime"));
        if(null!=list){
            for (HashMap m:list){
                m.put("hospitalId",userConfig.getHospitalId());
                m.put("details",orderService.queryOutpatientCostDetail(m.get("orderid").toString()));
            }
        }
        if(null!=list&&list.size()<=0){
            return R.ok(R.ERROR2,"查询成功,但没有信息");
        }
        R res=R.ok(R.OK_SUCCESS,"成功");
        res.putData(list);
        return res;
    }


    /**
     *  查询患者住院记录
     * @param pform  万能参数对象
     * @return
     */
    @RequestMapping(value = "queryHospitalizationRecord",method = {RequestMethod.POST})
    @ApiOperation("查询患者住院记录  testOk ")
    public Object queryHospitalizationRecord(@RequestBody Pform pform){

        if(null==pform){
            return R.error(R.ERROR3,"参数不能为空");
        }
        if(null==pform.getString("medicalCardNumber")){
            return R.error(R.ERROR3,"电子卡号不能为空");
        }
        if(null==pform.getString("startTime")){
            return R.error(R.ERROR3,"查询日期不能为空");
        }
        if(null==pform.getString("endTime")){
            return R.error(R.ERROR3,"查询日期不能为空");
        }

        HisUser  hisUser=brdaService.queryHisUserByMedicalCardNumber(pform.getString("medicalCardNumber"));
        if(null==hisUser&&null!=pform.getString("idCard")){
            hisUser=brdaService.queryHisUserByIdcard(pform.getString("idCard"));
        }
        if(null==hisUser){
            return R.error(R.ERROR3,"未查询到病人信息");
        }

        List<HashMap<String,Object>> list=apiV1Service.queryHospitalizationRecord(hisUser.getIdcard(),pform.getString("startTime"),pform.getString("endTime"));
        if(null!=list){
            for (HashMap<String,Object> m:list){
                m.put("hospitalId",userConfig.getHospitalId());
            }
        }
        if(null!=list&&list.size()<=0){
            return R.ok(R.ERROR2,"查询成功,但没有信息");
        }

        R res=R.ok(R.OK_SUCCESS,"成功");
        res.putData(list);
        return res;
    }




    /**
     *  根据住院记录 ID，查询住院费用明细
     * @param pform  万能参数对象
     * @return
     */
    @RequestMapping(value = "queryHospitalizationDetail",method = {RequestMethod.POST})
    @ApiOperation("根据住院记录 ID，查询住院费用明细  ")
    public Object queryHospitalizationDetail(@RequestBody(required = false) Pform pform){

        if(null==pform){
            return R.error(R.ERROR3,"参数不能为空");
        }
        if(null==pform.getString("id")){
            return R.error(R.ERROR3,"住院编号不能为空");
        }

        HashMap<String,Object> m=apiV1Service.queryHospitalization(pform.getString("id"));
        if(null!=m){
            m.put("details", apiV1Service.queryHospitalizationDetail(pform.getString("id")));
        }
        if(null==m){
            return R.ok(R.ERROR2,"查询成功,但没有信息");
        }
        R res=R.ok(R.OK_SUCCESS,"成功");
        res.putData(m);
        return res;
    }


    /**
     *  根据 id 获取某次住院记录费用概要信息
     * @param pform  万能参数对象
     * @return
     */
    @RequestMapping(value = "queryHospitalization",method = {RequestMethod.POST})
    @ApiOperation("根据 id 获取某次住院记录费用概要信息 （暂不支持） ")
    public Object queryHospitalization(@RequestBody(required = false) Pform pform){
        return R.error(R.ERROR3,"暂不支持");
    }


    /**
     *  根据 id 和时间查询患者某天住院费用的详细信息
     * @param pform  万能参数对象
     * @return
     */
    @RequestMapping(value = "queryHospitalizationXxxx",method = {RequestMethod.POST})
    @ApiOperation("根据 id 和时间查询患者某天住院费用的详细信息 （暂不支持） ")
    public Object queryHospitalizationXxxx(@RequestBody(required = false) Pform pform){
        return R.error(R.ERROR3,"暂不支持");
    }









    /***********************************   新增  ******************************************************/



    @RequestMapping(value = "refundQuery",method = {RequestMethod.POST})
    @ApiOperation("根据订单号查询是否可退款 (新增)")
    public Object refundQuery(@RequestBody(required = true) Pform pform){
        if(null==pform){
            return R.error(R.ERROR3,"参数不能为空");
        }
        if(null==pform.getString("medicalCardNumber")){
            return R.error(R.ERROR3,"电子卡号不能为空");
        }
        if(null==pform.getString("outTradeNo")){
            return R.error(R.ERROR3,"订单号不能为空");
        }

        List<OrderEntity> list=orderService.list(new QueryWrapper<OrderEntity>()
                .eq("outTradeNo",pform.getString("outTradeNo"))
        );

        if(null!=list&&list.size()>0){
            return R.error(R.ERROR2,"不可退款").putData("nonrefundable");
        }


        return R.ok().putData("refundable");
    }


    @RequestMapping(value = "statistics",method = {RequestMethod.POST})
    @ApiOperation("根据统计时间范围查询统计量 (新增)")
    public Object statistics(@RequestBody(required = true) Pform pform){
        if(null==pform){
            return R.error(R.ERROR3,"参数不能为空");
        }
        if(null==pform.getString("startTime")){
            return R.error(R.ERROR3,"开始时间不能为空");
        }
        if(null==pform.getString("endTime")){
            return R.error(R.ERROR3,"结束时间不能为空");
        }

        /**
         * 4、 outpatientTotalAmount 门诊总交易金额
         * 5、 outpatientTotalTrans 门诊总交易笔数
         * 6、 inpatientTotalAmount 住院总交易金额
         * 7、 inpatientTotalTrans 住院总交易笔数
         * 8、 regCardAmount 阶段时间内，具有电子健康卡的就诊人次
         * 9、 totalCardAmount 阶段时间内，总就诊人次（同一张卡使用多次按 1 次算）
         */

        R map=R.ok();
//        map.put("outpatientTotalAmount","0");
//        map.put("outpatientTotalTrans","0");
//        map.put("inpatientTotalAmount","0");
//        map.put("inpatientTotalTrans","0");
//        map.put("regCardAmount","0");
//        map.put("totalCardAmount","0");


        HashMap s=apiV1Service.statistics(pform.getString("startTime"),pform.getString("endTime"));
        map.putAll(s);

        return map;
    }








    /***********************************   暂未支持的相关接口  ******************************************************/







    @RequestMapping(value = "queryBalance",method = {RequestMethod.POST})
    @ApiOperation("获取就诊卡余额 (暂不支持)")
    public Object queryBalance(){
        return R.error(R.ERROR3,"暂不支持");
    }


    @RequestMapping(value = "paySuccess",method = {RequestMethod.POST})
    @ApiOperation("就诊卡充值 (暂不支持)")
    public Object paySuccess(){
        return R.error(R.ERROR3,"暂不支持");
    }


    @RequestMapping(value = "getRefundBlance",method = {RequestMethod.POST})
    @ApiOperation("获取就诊卡可退款金额 (暂不支持)")
    public Object getRefundBlance(){
        return R.error(R.ERROR3,"暂不支持");
    }

    @RequestMapping(value = "getCanRefund",method = {RequestMethod.POST})
    @ApiOperation("获取能否退款 (暂不支持)")
    public Object getCanRefund(){
        return R.error(R.ERROR3,"暂不支持");
    }


    @RequestMapping(value = "getRefundStatus",method = {RequestMethod.POST})
    @ApiOperation("获取退款状态 (暂不支持)")
    public Object getRefundStatus(){
        return R.error(R.ERROR3,"暂不支持");
    }

    @RequestMapping(value = "cardRefund",method = {RequestMethod.POST})
    @ApiOperation("就诊卡退款（用户发起） (暂不支持)")
    public Object cardRefund(){
        return R.error(R.ERROR3,"暂不支持");
    }


    @RequestMapping(value = "todayRegisterCancleRegister",method = {RequestMethod.POST})
    @ApiOperation("取消挂号 (暂不支持)")
    public Object todayRegisterCancleRegister(){
        return R.error(R.ERROR3,"暂不支持");
    }


    @RequestMapping(value = "todayRegisterQueuingInfo",method = {RequestMethod.POST})
    @ApiOperation("查询排队信息接口 (暂不支持)")
    public Object todayRegisterQueuingInfo(){
        return R.error(R.ERROR3,"暂不支持");
    }





}
